<?php
class SF_Catalog_Block_Product_List_Toolbar extends Mage_Catalog_Block_Product_List_Toolbar
{
    public function setCollection($collection)
    {
		$this->_collection = $collection;
        $this->_collection->setCurPage($this->getCurrentPage());
        $limit = (int)$this->getLimit();
        if ($limit) {
            $this->_collection->setPageSize($limit);
        }

        if ($this->getCurrentOrder()) {
			switch($this->getCurrentOrder()){
				case 'qty_ordered':
					$this->setOrderByOrder($this->_collection);
					break;
				case 'updated_at':
					$this->setOrderByNewest($this->_collection);
					break;
				case 'discount':
					$this->setOrderByDiscount($this->_collection);
					break;
				case 'rating_summary':
					$this->setOrderByRating($this->_collection);
					break;
				default:
					$this->_collection->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());
					break;
			}
        }
        return $this;
		
    }
	
	private function setOrderByOrder($collection){
		
		$collection->getSelect()
			->joinLeft(
				array('sfoi' => $collection->getResource()->getTable('sales/order_item')),//表名
				'e.entity_id = sfoi.product_id',//连接条件
				array('qty_ordered' => 'SUM(sfoi.qty_ordered)')//选择出的字段
			)
			->where("sfoi.parent_item_id is NUll")
			->group('e.entity_id')
			->order('qty_ordered ' . $this->getCurrentDirection());
		
		return $this;
	}
	
	private function setOrderByNewest($collection){
		
		$collection->setOrder('updated_at',$this->getCurrentDirection());
		return $this;
	}
	
	private function setOrderByDiscount($collection){

		$collection->getSelect()
			->joinLeft(
				array('sfoi' => 'catalog_product_index_price'),//表名
				'e.entity_id = sfoi.entity_id',//连接条件
				array('discount' => '(sfoi.price-sfoi.final_price)/sfoi.price')//选择出的字段
			)
			->group('e.entity_id')
			->order('discount ' . $this->getCurrentDirection());
		return $this;
	}
	private function setOrderByRating($collection){
		
		$collection->getSelect()
			->joinLeft(
				array('sfoi' => 'review_entity_summary'),//表名
				'e.entity_id = sfoi.entity_pk_value',//连接条件
				array('rating_summary' => 'sfoi.rating_summary')//选择出的字段
			)
			->group('e.entity_id')
			->order('rating_summary ' . $this->getCurrentDirection());
		return $this;
	}
}